const Model = require('./index')

class UserModel extends Model {
  /**
   * 分页查询用户列表
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} andConditions
   * @param {*} orConditions
   * @param {*} betweenConditions
   * @returns
   */
  async findPage ({ pageNo, pageSize, andConditions, orConditions, betweenConditions }) {
    const andSql = this.generateWhereClause(andConditions)
    const completeSql = this.generateBetweenClause(betweenConditions, this.generateWhereClauseOR(orConditions, andSql))
    const sql = `select * from user ${completeSql}
      order by user.createTime desc
      limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(completeSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  async updateStatus (id, status) {
    const sql = 'update user set status = ? where id = ?'
    try {
      await this.db.query(sql, [status, id])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 更新用户基本信息
   * @param {*} id
   * @param {*} param1
   */
  async update (id, { nickname, gender, avatar, age, job, description }) {
    const updateTime = this.dateFormat(new Date())
    const { columnSet, values } = this.multipleColumnSet({ nickname, gender, avatar, age, job, description, updateTime }, false)
    const sql = `update user set ${columnSet} where id = ?`
    try {
      await this.db.query(sql, [...values, id])
    } catch (error) {
      throw new Error(error)
    }
  }

  async total (conditionSql) {
    const sql = `select count(*) as total from user ${conditionSql}`
    try {
      const data = await this.db.query(sql)
      return data[0].total
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new UserModel('user')
